<?php

namespace App\Http\Controllers;

use App\UserModel;
use http\Client\Curl\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function addInfo(Request $request)
    {
        $inputs = $request->input();
        $headimg = $request->file('headimg');
        $headImgUrl = "";
        if ($headimg){
            foreach ($headimg as $img){
                $headImgUrl .= $this->fileUploader('uploads',$img);
            }
            $inputs['headimg'] = $headImgUrl;
        }
        unset($inputs['_token']);
        if($inputs['id']==0){
            $res = UserModel::create($inputs);
            if($res){
                $res = "写入数据库成功！";
            }
        }else{
            $user = UserModel::find($inputs['id']);
            $user->headimg = explode(';',$user->headimg);
            $userImg = $user->headimg;
            array_pop($userImg);
            foreach ($userImg as $img){
                unlink($img);
            }
            $user->update($inputs);
            $res = "数据更新成功！";
        }
        return view("donePage",compact('res'));
    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $user = UserModel::find($id);
        $user->delete();
        $res = "删除成功！";
        return view('donePage',compact('res'));
    }

    public function fileUploader($folder,$file)
    {
        $fileName = date('YmdHis').rand(100,999).".".$file->getClientOriginalExtension();
        $file->move(public_path($folder),$fileName);
        $fileSRC = $folder."/".$fileName.';';
        return $fileSRC;
    }

    public function detail(Request $request)
    {
        $id = $request->input('id');
        $user = UserModel::find($id)->toArray();
        $user['headimg'] = explode(';',$user['headimg']);
        array_pop($user['headimg']);
        return view('detail',compact('user'));
    }
}
